
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/core/view/lc_fullscreen_widget.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

import '../../core/view/agreement_widget.dart';

class LoginRegisterPage extends StatefulWidget {
  const LoginRegisterPage({Key? key}) : super(key: key);

  @override
  State<LoginRegisterPage> createState() => _LoginRegisterPageState();
}

class _LoginRegisterPageState extends State<LoginRegisterPage> {

  TextEditingController _emailController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  TextEditingController _comfirmPwdController = TextEditingController();
  TextEditingController _smsController = TextEditingController();

  TimerUtil? mTimerUtil;
  int mTick = 120;
  int totalTime = 120; // 120s

  // 刷新个人信息定时器

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    mTimerUtil =
        TimerUtil(mInterval: 1000, mTotalTime: totalTime * 1000); // 时间间隔 ms

    if(LocalStorage.getIsCheckAgreement() == false){
      getAgreement(context, () {
        LocalStorage.setIsCheckAgreement(true);
      });
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    mTimerUtil?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            child: LCFullScreen(child: Image.asset(IconNames.login_bg, fit: BoxFit.fill, )),
          ),

          Positioned(
            left: 15,
            top: MainCommon.statusBarHeight + 10,
            child: InkWell(
              onTap: () {
                Get.back();
              },
              child: Container(
                padding: EdgeInsets.all(10),
                child: Icon(Icons.arrow_back_ios, size: 25, color: Colors.white,),
              ),
            ),
          ),

          Positioned(
            top: 80,
            child: Image.asset(IconNames.login_logo, width: 180,)
          ),

          Container(
            margin: EdgeInsets.fromLTRB(50, 100 + 40, 50, 0),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      SizedBox(height: 10,),
                      // 邮箱
                      TextField(
                        controller: _emailController,
                        decoration: InputDecoration(
                          hintText: "Email",
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          filled: true,
                          fillColor: Color(0xFF3E3A39),
                          hintStyle: TextStyle(color: Colors.grey),
                        ),
                        style: TextStyle(color: Colors.grey),
                        cursorColor: Colors.grey,
                        onSubmitted: (value) {
                          print("onSubmitted:$value");
                        },
                      ),
                      SizedBox(height: 10,),
                      // 验证码
                      Stack(
                        children: [
                          TextField(
                            controller: _smsController,
                            decoration: InputDecoration(
                              hintText: "Code",
                              contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10),
                                borderSide: BorderSide(color: Colors.grey, width: 1),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10),
                                borderSide: BorderSide(color: Colors.grey, width: 1),
                              ),
                              filled: true,
                              hintStyle: TextStyle(color: Colors.grey),
                              fillColor: Color(0xFF3E3A39),
                            ),
                            style: TextStyle(color: Colors.grey),
                            cursorColor: Colors.grey,
                            onSubmitted: (value) {
                              print("onSubmitted:$value");
                            },
                          ),
                          Positioned(
                            right: 5,
                            top: 4,
                            child: Container(
                              height: 40,
                              child: ElevatedButton(

                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(MainCommon.homeBtnColor),
                                  shape: MaterialStateProperty.all(
                                      RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))
                                  ),
                                  padding: MaterialStateProperty.all(EdgeInsets.symmetric(horizontal: 7))
                                ),
                                child: Text(mTick == totalTime ? LocaleKeys.login_sms_code.trc() : '${mTick}s', style: TextStyle(color: mTick == totalTime ? Colors.white: Colors.white, fontSize: 15),),
                                onPressed: mTick == totalTime ? () {
                                  _getSMSCode();
                                  // 开启倒计时
                                  mTimerUtil?.startCountDown();

                                  mTimerUtil?.setOnTimerTickCallback((int tick) {
                                    double _tick = tick / 1000;

                                    setState(() {
                                      mTick = _tick.toInt();
                                    });

                                    if (_tick.toInt() == 0) {
                                      //重置时间
                                      mTimerUtil?.setTotalTime(totalTime * 1000);
                                      mTimerUtil?.cancel();
                                      logs("取消倒计时");

                                      setState(() {
                                        mTick = totalTime;
                                      });
                                    }
                                  });

                                } : null,
                              ),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 10,),
                      // 密码
                      TextField(
                        obscureText: true,
                        controller: _pwdController,
                        decoration: InputDecoration(
                          hintText: "Password",
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          filled: true,
                          hintStyle: TextStyle(color: Colors.grey),
                          fillColor: Color(0xFF3E3A39),
                        ),
                        style: TextStyle(color: Colors.grey),
                        cursorColor: Colors.grey,
                        onSubmitted: (value) {
                          print("onSubmitted:$value");
                        },
                      ),
                      SizedBox(height: 10,),
                      // 确认密码
                      TextField(
                        obscureText: true,
                        controller: _comfirmPwdController,
                        decoration: InputDecoration(
                          hintText: "Confirm Password",
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          filled: true,
                          hintStyle: TextStyle(color: Colors.grey),
                          fillColor: Color(0xFF3E3A39),
                        ),
                        style: TextStyle(color: Colors.grey),
                        cursorColor: Colors.grey,
                        onSubmitted: (value) {
                          print("onSubmitted:$value");
                        },
                      ),

                      SizedBox(height: 20,),

                      InkWell(
                          onTap: () {  // 开始注册
                            _startRegister();
                          },
                          child: Image.asset(IconNames.login_go, width: 70,)
                      ),
                    ],
                  ),

                ],
              ),
            ),
          ),

          Positioned(
            bottom: 10,
              child: Container(
                child: Image.asset(IconNames.login_logo02, width: 100,),
              ),
          ),
        ],
      ),
    );
  }

  _getSMSCode() async {
    if(_emailController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_email.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    final params = {"email": _emailController.text, "type": "1"};
    ResultData data = await AppApi.getInstance().sendSMS(params);
    if(data.code == 0){  // 请求成功

    }else{
      SmartDialog.showToast(data.msg);
    }
  }

  _startRegister() async {
    if(_emailController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_email.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    if(_smsController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_sms_code.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    if(_pwdController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_password.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    if(_comfirmPwdController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_password.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    if(_comfirmPwdController.text != _pwdController.text) {
      SmartDialog.showToast(LocaleKeys.other_password_tip.trc());
      return;
    }

    final params = {"email": _emailController.text,
      "password": _comfirmPwdController.text,
      "code": _smsController.text,
    };
    ResultData data = await AppApi.getInstance().startRegister(params);
    if(data.code == 0){  // 请求成功
      SmartDialog.showToast("Success");
      Get.back();
    }else{
      SmartDialog.showToast(data.msg);
    }
  }
}
